package org.realogic.cfm.util;

import java.sql.Timestamp;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;

public final class SqlTimestampConverter implements Converter {

	// ----------------------------------------------------------- Constructors

	public SqlTimestampConverter() {

		this.defaultValue = null;
		this.useDefault = false;

	}

	public SqlTimestampConverter(Object defaultValue) {

		this.defaultValue = defaultValue;
		this.useDefault = true;

	}

	// ----------------------------------------------------- Instance Variables

	private Object defaultValue = null;

	private boolean useDefault = true;

	// --------------------------------------------------------- Public Methods

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object convert(Class type, Object value) {

		if (value == null || value.equals("") || value.equals("null")) {
			if (useDefault) {
				return (defaultValue);
			} else {
				// throw new ConversionException("No value specified");
				return null;
			}
		}

		if (value instanceof Timestamp) {
			return (value);
		}

		try {
			return (Timestamp.valueOf(value.toString()));
		} catch (Exception e) {
			if (useDefault) {
				return (defaultValue);
			} else {
				throw new ConversionException(e);
			}
		}

	}

}
